<%-- 
    Document   : manage_users
    Created on : 22 лют 2012, 21:42:50
    Author     : vlavrynovych
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<script type="text/javascript" src="js/fieldsChecker.js"></script>
<script type="text/javascript">
    var addEditUserFieldChecker;
    var $dialogUserId;
    var $dialogIsUserEnabled;
    var $userListTable;
    var $userEditErrorDiv;
    var $userAddErrorDiv;
    var $addEditUserDialog;
    
    // request config
    var userReq = {
        name: "",
        email: "",
        enabled: "",
        startIndex: 0,
        size: defaultListSize,
        showAll: false
    };
    
    //pager buttons
    var $userPrev;
    var $userNext;
    
    $(document).ready(function() {
        // pager
        $userPrev = $('#userPagerPrevButton');
        $userNext = $('#userPagerNextButton');
        
        $dialogUserId = $("#dialogUserId");
        $dialogIsUserEnabled = $("#isUserEnabled");
        $userListTable = $("#userList");
        $userEditErrorDiv = $("#userModificationError");
        $userAddErrorDiv = $("#errorDiv");
        $addEditUserDialog = $("#addEditUserDialog");
        addEditUserFieldChecker = new fieldsChecker("dialogLogin", "dialogPassword", "dialogEmail", "dialogLoginError", "dialogPasswordError", "dialogEmailError");
        
        userRequest();
    })
    
    function showAddEditUserDialog(userId) {
        $dialogRoles.attr("checked", false);
        $dialogIsUserEnabled.find("input").attr("checked", false).removeAttr("disabled");
        addEditUserFieldChecker.$password.val("");
        $addEditUserDialog.modal();

        //sets  title for modal dialog
        $addEditUserDialog.find('#modalTitle').text((userId ? "Edit" : "Add") + " User");

        $addEditUserDialog[0].isEdit = userId;

        if(userId!=null){
            var $userData = getUserRow(userId);
            $dialogUserId.html(userId);
            addEditUserFieldChecker.$login.val($userData.find("td:nth-child(3)").html());
            addEditUserFieldChecker.$email.val($userData.find("td:nth-child(5)").html());
            var rolesArray = new Array();
            var $roles = $userData.find("td:nth-child(4) div").each(function() {
                rolesArray.push($(this).html());
            });
            $dialogRoles.each(function() {
                var $elem = $(this).next("span");
                for(var j = 0; j < rolesArray.length; j++) {
                    if($elem.html() == rolesArray[j]) {
                        $elem.prev("input").attr("checked", true);
                        break;
                    }
                }
            });
            if($.trim($userData.find("td:nth-child(6)").html()) == "true") {
                $($dialogIsUserEnabled.find("input")[0]).attr("checked", true);
            } else {
                $($dialogIsUserEnabled.find("input")[1]).attr("checked", true);
            }
        } else {
            $($dialogIsUserEnabled.find("input")).attr("checked", false).attr("disabled", true);
        }
    }
    
    function userRequest(showAll){
        var preparedData;
        if(showAll){
            preparedData = {
                name: "",
                email: "",
                enabled: "",
                startIndex: 0,
                size: 0
            }
            userReq.showAll = true;
        } else {
            preparedData = {
                name: userReq.name,
                email: userReq.email,
                enabled: userReq.enabled,
                startIndex: userReq.startIndex,
                size: userReq.size
            }
            userReq.showAll = false;
        }
        
        $.ajax({
            url: "searchUsers.html",
            data: preparedData,
            success: function(list, status) {
                if(status=="success"){
                    if(showAll){
                        $userListTable.find("tr[id]").remove();
                        $userPrev.attr("disabled",true);
                        $userNext.attr("disabled",true);
                        
                        if(list.length>0){
                            $.each(list, function(index, user){
                                addUpdateUserRow(user, index+1);
                            });
                        } else {
                            noRecordsFound($userListTable, 7);
                        }
                    } else {
                        $userListTable.find("tr[id]").remove();
                        $userPrev.attr("disabled",userReq.startIndex==0);
                        $userNext.attr("disabled",list.length!=userReq.size+1);

                        if(list.length>0){
                            $.each(list, function(index, user){
                                if(index<userReq.size){
                                    addUpdateUserRow(user, userReq.startIndex+index+1);
                                }
                            });
                        } else {
                            noRecordsFound($userListTable, 7);
                        }
                    }
                }
            }
        });
        
        refreshUserCount();
    }
    
    function showAllUsers(){
        userRequest(true);
    }

    function userSearch(){
        userReq.name = $('#search_name').val();
        userReq.email = $('#search_email').val();
        userReq.enabled = $('#search_is_enabled').val();
        userReq.startIndex = 0;
        userRequest();
    }
    
    // shows previous user list page
    function userPagerNext(){
        if(!$userNext.attr("disabled")){
            userReq.startIndex = userReq.startIndex+userReq.size;
            userRequest();
        }
    }
    
    // shows next user list page
    function userPagerPrev(){
        if(!$userPrev.attr("disabled")){
            userReq.startIndex = userReq.startIndex-userReq.size;
            userRequest();
        }
    }
    
    function onOkUserModal() {
        if(addEditUserFieldChecker.checkFields()) {

            // collects all roles
            var roles = "";
            $dialogRoles.parent().find("input:checked").each(function() {
                roles += $(this).val() + ",";
            });
            roles = roles.substring(0, roles.length - 1);

            if ($addEditUserDialog[0].isEdit){
                //edits current user
                $.ajax({
                    url: "edit_user.html",
                    data: {id: $dialogUserId.html(),
                        login: $.trim(addEditUserFieldChecker.$login.val()),
                        password: $.trim(addEditUserFieldChecker.$password.val()),
                        email: $.trim(addEditUserFieldChecker.$email.val()),
                        isEnabled: $dialogIsUserEnabled.find("input:checked").val(),
                        roles: roles},
                    success: function(resultMsg) {
                        if(resultMsg == "ok") {
                            userRequest();
                            $userEditErrorDiv.html("").fadeOut();
                            onCancelUserModal();
                            Notifier.success("User was successfully updated!");
                        } else {
                            $userEditErrorDiv.html(resultMsg).fadeIn();
                            Notifier.error("User was not updated.");
                        }
                    }
                });
            } else {
                // adds new user
                $.ajax({
                    url: "add_user.html",
                    data: {name: $.trim(addEditUserFieldChecker.$login.val()), 
                        password: $.trim(addEditUserFieldChecker.$password.val()),
                        roles: roles,
                        email: $.trim(addEditUserFieldChecker.$email.val())},
                    success: function(resultMsg) {
                        if(resultMsg == "ok") {
                            userRequest(userReq.showAll);
                            onCancelUserModal();
                            Notifier.success("User was added.");
                        } else {
                            $userEditErrorDiv.html(resultMsg).fadeIn();
                            Notifier.error("User was not added.");
                        }
                    }
                });
            }
        }
    }
    
    function onCancelUserModal() {
        $addEditUserDialog.modal("hide");
        clearUserInputs();
        $userEditErrorDiv.html("").fadeOut();
    }
    
    function clearUserInputs() {
        addEditUserFieldChecker.clearAll();
        $dialogRoles.attr("checked", false);
    }
       
    function addUpdateUserRow(user, number){
        if (!user) return;
        var $row = getUserRow(user.id);
        if ($row[0]==undefined){
            $row = addEmptyUserRow(user.id, number)
        }

        //prepares roles
        var roles = "";
        for(var i = 0; i < user.roles.length; i++) {
            roles += "<div>" + user.roles[i].name + "</div>";
        }

        // updates all values
        $row.find("td:nth-child(3)").html(user.name);
        $row.find("td:nth-child(4)").html(roles);
        $row.find("td:nth-child(5)").html(user.email);
        $row.find("td:nth-child(6)").html(""+user.enabled);
        $row.find("td:nth-child(7)").html(user.creationDate);
    }
    
    // adds one empty row with user ID
    function addEmptyUserRow(userId, number){
        var row = $("<tr>");
        row.attr('id',userId);
        
        var numberCell = $("<td>").html(number);
        row.append(numberCell);

        var actionsCell = $("<td>").html('&nbsp;');
        if(userId!=1){
            var editButton = $('<a>');
            editButton.attr('onclick','showAddEditUserDialog('+userId+')');
            editButton.attr('class','icon-edit');
            editButton.attr('title','Edit').tooltip();
            actionsCell.prepend(editButton);

            var deleteButton = $('<a>');
            deleteButton.attr('onclick','deleteUserById('+userId+')');
            deleteButton.attr('class','icon-trash');
            deleteButton.attr('title','Delete').tooltip();
            actionsCell.append(deleteButton);
        } else {
            actionsCell = $("<td>");
            actionsCell.append($('<a>').attr('class','icon-ban-circle'));
        }
        
        row.append(actionsCell); //actions cell

        //adds other cells
        for(var i = 0; i < 5; i++) {
            row.append($("<td>"));
        }

        $userListTable.append(row);
        return row;
    }
    
    function getUserRow(userId){
        return $userListTable.find($('#'+userId));
    }

    function deleteUserById(id) {
        $.ajax({
            url: "remove_user/" + id + ".html",
            success: function(resultMsg) {
                hideAllTooltips();
                if(resultMsg == "ok") {
                    userRequest();
                    Notifier.success("User was successfully deleted!");
                }
            }
        });
    }
</script>

<div style="width: 94%; margin-left: 3%; margin-right: 3%">
    <fieldset>
        <form class="well form-inline">
            <span>
                <a class="btn btn-primary" onclick="showAddEditUserDialog()"><i class="icon-plus icon-white"></i> Add User</a>
                <a class="btn" id="userPagerPrevButton" onclick="userPagerPrev()">Previous</a>
                <a class="btn" id="userPagerNextButton" onclick="userPagerNext()">Next</a>
            </span>
            <span class="pull-right">
                <input id="search_name" type="text" class="input-small" placeholder="Name">
                <input id="search_email" type="text" class="input-small" placeholder="Email">
                <label class="control-label" for="search_is_enabled">Enabled?</label>
                <select class="span1" id="search_is_enabled">
                    <option selected="true" value="">&nbsp;</option>
                    <option value="true">Yes</option>
                    <option value="false">No</option>
                </select>
                <a class="btn" onclick="userSearch()"><i class="icon-search"></i> Search</a>
                <a class="btn" onclick="userRequest(userReq.showAll)"><i class="icon-refresh"></i> Refresh</a>
                <a class="btn" onclick="showAllUsers()"><i class="icon-refresh"></i> Show All</a>
            </span>
        </form>
        <div id="userModificationError"></div>
        
        <table class="table table-striped table-condensed table-bordered" id="userList">
            <thead>
                <tr style="background-color: #666666; color: white">
                    <th style="width: 20px">#</th>
                    <th style="width: 35px"><i class="icon-cog icon-white"/></th>
                    <th style="width: 150px">Login</th>
                    <th>Roles</th>
                    <th style="width: 250px">Email</th>
                    <th style="width: 50px">Enabled</th>
                    <th style="width: 120px">Modification date</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        
    </fieldset>
</div>

<!-- Edit user dialog section -->
<div id="addEditUserDialog" class="modal hide fade" style="display: table">
    <div class="modal-header">
        <a class="close" data-dismiss="modal">×</a>
        <h3 id="modalTitle"></h3>
    </div>

    <div class="modal-body form-horizontal">
        <div id="dialogErrorDiv" class="alert alert-error" style="display: none"></div>
        <span id="dialogUserId" style="display: none"></span>
        <div class="control-group">
            <label for="login" class="control-label">Login</label>
            <div class="controls">
                <input type="text" id="dialogLogin">
                <p class="help-block">Specify minimum 4 symbols</p>
            </div>
            <div id="dialogLoginError" class="alert alert-block" style="display:none;">
                <a class="close">×</a>
                <h4 class="alert-heading">Warning!</h4>
                Login is incorrect
            </div>
        </div>

        <div class="control-group">
            <label for="password" class="control-label">Password</label>
            <div class="controls">
                <input type="password" id="dialogPassword">
                <p class="help-block">Specify minimum 4 symbols</p>
            </div>
            <div id="dialogPasswordError" class="alert alert-block" style="display:none;">
                <a class="close">×</a>
                <h4 class="alert-heading">Warning!</h4>
                Password is incorrect
            </div>
        </div>

        <div class="control-group">
            <label for="email" class="control-label">Email</label>
            <div class="controls input-prepend">
                <input type="text" id="dialogEmail"/>        
            </div>
            <div id="dialogEmailError" class="alert alert-block" style="display:none;">
                <a class="close">×</a>
                <h4 class="alert-heading">Warning!</h4>
                Email is incorrect
            </div>
        </div>

        <div class="control-group">
            <label for="isUserEnabled" class="control-label">Enabled</label>
            <div id="isUserEnabled" class="controls">
                <label class="radio">
                    <input type="radio" value="1" name="isEnabled" checked="checked" />&nbsp;Yes
                </label>
                <label class="radio">
                    <input type="radio" value="0" name="isEnabled" />&nbsp;No
                </label>
            </div>
        </div>
        
        <div class="control-group">
            <label for="dialogRoles" class="control-label">Roles</label>
            <div id="dialogRoles" class="controls">
                <div class="table table-bordered" style="width: 300px; height: 150px; overflow: auto; padding: 10px">
                    <c:forEach items="${availableRoles}" var="role">
                        <label class="checkbox">
                            <input type="checkbox" value="${role.id}" name="roles"/>&nbsp;<span>${role.name}</span>
                        </label>
                    </c:forEach>
                </div>
            </div>
        </div>
    </div>

    <div class="modal-footer">
        <a class="btn" onclick="clearUserInputs()"><i class="icon-remove-circle"></i> Clear</a>
        <input type="button" class="btn" onclick="onCancelUserModal()" value="Cancel"/>
        <input type="button" class="btn btn-primary" onclick="onOkUserModal()" value="Ok"/>
    </div>
</div>
<!-- End edit user dialog section -->